<template>
  <van-button
    :loading="followLoading"
    @click="onFollow"
    class="follow-btn"
    round
    size="small"
    v-if="isFollowed "
  >已关注</van-button>
  <van-button
    :loading="followLoading"
    @click="onFollow"
    class="follow-btn"
    color="#3296fa"
    icon="plus"
    round
    size="small"
    type="info"
    v-else
  >关注</van-button>
</template>
<script>
import { addFollow, deleteFollow } from '@/api/user'

export default {
  name: 'FollowUser',
  model: {
    prop: 'isFollowed',
    event: 'update-is_followed'
  },
  props: {
    isFollowed: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data () {
    return {
      followLoading: false
    }
  },
  methods: {
    async onFollow () {


      try {
        // 展示关注按钮的loading
        this.followLoading = true
        // 如果已关注，则取消关注
        const authorId = this.userId
        if (this.isFollowed) {
          const { data: res } = await deleteFollow(authorId)
          console.log(res)

        } else {
          // 否则添加关注
          const { data: res } = await addFollow(authorId)
          console.log(res)
        }

        // 更新视图
        this.$emit('update-is_followed', !this.isFollowed)


      } catch (err) {
        console.log(err)
        let message
        if (err.response && err.response.status === 400) {
          message = '不能关注自己'
        }
        this.$toast.fail(message)
      }
      // 关闭loading
      this.followLoading = false

    },
  }
}
</script>
<style lang="less" scoped>
</style>